/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package serverimplementation;
import java.util.HashMap;
import java.util.Scanner;
import java.net.*;
import java.io.*;
import java.lang.String.*;
import java.util.ArrayList;
/**
 *
 * @author manish
 */
public class Main{
    private HashMap<String,User> HashInstance=new HashMap();
    private HashMap<String,String> HashPass = new HashMap();
    private HashMap<String, String> HashIPAddress=new HashMap();
    private HashMap<String, Integer> HashPortNumbers=new HashMap();
    //private HashMap UserName= new HashMap();
    // Work on this UserName HashMap
    //static int option=-1;
    static int fileCheck=0;
    //static String firstName=null;
    //static String lastName=null;
    //static String email=null;
    static String UserId=null;
    static String password=null;
    static String BuddyId=null;
    
    ServerSocket theServer = null;
    Socket communicator = null;
    BufferedReader in;
    PrintWriter out;
    String inputString;
    String cmd;
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException{
        // TODO code application logic here
        Scanner input = new Scanner(System.in);
        Main server=new Main();
        try{
            ServerSocket theServer = new ServerSocket(2000);
            System.out.println("Socket set up");
            boolean finished = false;
              while (!finished) {
                  server.communicator = theServer.accept();
                  System.out.println("connection received");
                  server.in = new BufferedReader(new InputStreamReader(server.communicator.getInputStream()));
                  server.out = new PrintWriter(server.communicator.getOutputStream(), true);
                  server.inputString = server.in.readLine();
                  System.out.println("message: " + server.inputString);
                  //System.out.println("Sending response");
                  String [] temp=null;
                  //System.out.println("Calling break string to extract string");
                  temp=(String[]) server.breakString(server.inputString);
                  System.out.println("cmd:"+temp[0]);
                  //server.writeFile("Hi First Line");
                  //server.readFile();
                  if (temp[0].equalsIgnoreCase("Registration")){
                      //System.out.println("Identified registration method and calling its method");
                      server.registration(server.inputString);
                  }
                  
                  else if (temp[0].equalsIgnoreCase("LogIN")){
                      server.logIn(server.inputString);
                  }
                  else if (temp[0].equalsIgnoreCase("LogOut")){
                      server.logout(server.inputString);
                  }
                  else if (temp[0].equalsIgnoreCase("Add Buddy")){
                      server.addBuddy(server.inputString);
                  }
                  else if (temp[0].equalsIgnoreCase("Remove Buddy")){
                      server.removeBuddy(server.inputString);
                  }
                  else if (temp[0].equalsIgnoreCase("Get IP Address")){
                      server.getIPAddress(server.inputString);
                  }
                  else if(temp[0].equalsIgnoreCase("Get Port number")){
                      server.getPortNumber(server.inputString);
                  }
                  else if(temp[0].equalsIgnoreCase("CheckBuddyOnline")){
                      server.checkBuddyOnline(temp[1]);
                  }
                  else{
                      System.out.println("Cannot Identify packet send from Sender");
                      //server.out.println("Cannot Identify packet send from Sender");
                  }
              }
        }
        catch (IOException e)
        {
                System.out.println("Error occurred in communication");
                System.exit(1);
        }
        
        /*
        while(option!=0){
            System.out.println("Enter 1 for registration\nEnter 2 to login\nEnter 3 to LogOff");
            System.out.println("Enter 4 to If buddy is online\nEnter 5 to Add Buddy\n Enter 6 to remove Buddy");
            System.out.println("Enter your option now:");
            option=input.nextInt();
            input.nextLine();
            
            if (option==1){
                System.out.println("Enter your FirstName:");
                String firstName = input.nextLine();
                System.out.println("Enter your LastName:");
                String lastName = input.nextLine();
                System.out.println("Enter email:");
                String email =input.nextLine();
                System.out.println("Enter UsedId:");
                UserId= input.nextLine();
                while (server.HashInstance.containsKey(UserId)){
                    System.out.println("Please enter different UserID:");
                    UserId= input.nextLine();
                }
                System.out.println("Enter Password:");
                password =input.nextLine();
                server.registration(server.inputString);
            
            }
            else if (option==2){
                System.out.println("Enter UserId:");
                UserId=input.nextLine();
                if (server.HashInstance.containsKey(UserId)==false){
                        System.out.println("User doesn't exit");
                    }
                else{
                    System.out.println("Enter Password:");
                password=input.nextLine();
                if (server.HashInstance.isEmpty()){
                    System.out.println("Please Register First");
                }
                else{
                    server.logIn(UserId,password);
                }
                }
                
            
        }
            else if (option==3){
                if (server.HashInstance.isEmpty()){
                    System.out.println("Please Register First");
                }
                else{
                    System.out.println("Enter your User ID:");
                    UserId=input.nextLine();
                    if (server.HashInstance.containsKey(UserId)==false){
                        System.out.println("User doesn't exit");
                    }
                    else if(server.HashInstance.get(UserId).getStatus()){
                        server.logout(UserId);
                    }
                    else{
                    System.out.println("Please LogIn First");
                    }
                }
                
                
                
            }
            else if(option==4){
                if (server.HashInstance.isEmpty()){
                    System.out.println("Please Register First");
                }
                else{
                    System.out.println("Enter User ID:");
                    UserId=input.nextLine();
                    System.out.println("Enter Buddy Id");
                    String BuddyId=input.nextLine();
                    //System.out.println("Return Type:"+""+server.HashInstance.containsKey(BuddyId));
                    if (server.HashInstance.containsKey(UserId)==false){
                        System.out.println("User doesn't exit");
                    }
                    else{
                        if(server.HashInstance.containsKey(BuddyId)==false){
                        System.out.println("Buddy Id Doesn't exits, please try again later");
                        }
                        else{
                            //System.out.println("Return Type:"+""+server.HashInstance.get(UserId).checkBuddy(BuddyId));
                            if (server.HashInstance.get(UserId).checkBuddy(BuddyId)==false){
                                System.out.println("Not your Buddy Sorry!");
                            }
                            else{
                                server.checkStatusBuddy(BuddyId);
                            }
                        }
                        
                    }
                    
                }
                
            }
            else if(option==5){
                if (server.HashInstance.isEmpty()){
                    System.out.println("Please Register First");
                }
                else{
                    System.out.println("Enter your the User ID:");
                    UserId=input.nextLine();
                    System.out.println("Enter Buddy Id");
                    String BuddyId=input.nextLine();
                    if (server.HashInstance.containsKey(BuddyId)==false){
                        System.out.println("User doesn't exit");
                    }
                    else if(server.HashInstance.containsKey(BuddyId)==false){
                        System.out.println("Buddy Doesn't exit, please try again later");
                        BuddyId=input.nextLine();
                    }
                    else{
                        server.addBuddy(UserId, BuddyId);
                    }
                }
                
                
            }
            else if(option==6){
                if (server.HashInstance.isEmpty()){
                    System.out.println("Please register first");
                }
                else{
                    System.out.println("Enter User ID:");
                    UserId=input.nextLine();
                    System.out.println("Enter Buddy Id");
                    String BuddyId=input.nextLine();
                    if (server.HashInstance.containsKey(BuddyId)==false){
                        System.out.println("User doesn't exit");
                    }
                    else if(server.HashInstance.containsKey(BuddyId)==false){
                        System.out.println("Buddy doesn't Exit, Please try again later");
                        //BuddyId=input.nextLine();
                    }
                    else{
                        if (server.HashInstance.get(UserId).checkBuddy(BuddyId)==false){
                            System.out.println("Not your Buddy Sorry!");
                        }
                        else{
                            server.removeBuddy(UserId, BuddyId);
                        }
                        
                    }
                }
                
            }
            else if(option>6){
                System.out.println("The option number entered is invalid");
            }
       
}//While loop closed Brackets
        */
}//Main closed Brakets
    
    
public void readFile(){
    // Stream to read file
    FileInputStream fin;

    try {
        System.out.println("File reading loading...");
        fin = new FileInputStream("myfile.txt");
        DataInputStream stream=new DataInputStream(fin);
        String line=null;
        while (( line = stream.readLine()) != null){
            System.out.println(line);//stream.readLine());
        }        
        fin.close();
    }
    catch (IOException e) {
        System.err.println("Unable to read from file");
        System.exit(-1);
    }
}

public String getString(String userId, String password){
    String fileString = null;
    fileString =userId+","+password;
    return fileString;
}

public void writeFile(String userId, String password){
    
    
    if (!(new File("myfile.txt").exists())) { 
            try {
                FileOutputStream fout=new FileOutputStream("myfile.txt");
                PrintStream stream =new PrintStream(fout);//.println(temp);
                stream.println(getString(userId,password));
                fout.close();
                //System.out.println("File created successfully");
    } 
    catch (IOException e) {
        System.err.println("Unable to write to file");
        System.exit(-1);
    }
    }
    else{
        try{
            FileWriter fout1 = new FileWriter("myfile.txt", true);
            PrintWriter stream1 =new PrintWriter(fout1,true);//.println(temp);
            stream1.println(getString(userId,password));
            fout1.close();
        }
        catch(IOException e){
            
        }
    }


}

public void checkBuddyOnline(String BuddyId){
    String output=null;
    output=checkOnline(BuddyId);
    out.println(output);
}

public Object breakString(String s){
        String [] temp=null;
        temp=s.split(",");
        return temp;
}
public String returnUserId(String s){
    String [] temp=null;
    temp= (String[]) breakString(s);
    if (temp[0].equalsIgnoreCase("registration")){
        UserId=temp[3];
        //password=temp[10];
        return UserId;
    }
    else if(temp[0].equalsIgnoreCase("login")){
        UserId=temp[1];
        //password=temp[2];
        return UserId;
    }
    else {
        //I need to edit this
        return UserId;
    }
    
}
private void registration(String registrationString) {
    //System.out.println("Inside registration method");
    String [] temp=null;
    temp= (String[]) breakString(registrationString);
    UserId=temp[3];
    password=temp[10];
    if (HashInstance.containsKey(UserId)){
        //System.out.println("Please enter Different UserID");
        out.println("Please enter Different UserID");
    }
    else{
        User client = new User();
        
        client.setFirstName(temp[1]);
        client.setLastName(temp[2]);
        client.setUserId(temp[3]);
        client.setEmail(temp[4]);
        client.setGender(temp[5]);
        client.setMonth(temp[6]);
        client.setDate(temp[7]);
        client.setYear(temp[8]);
        client.setZip(temp[9]);
        client.setPassword(temp[10]);
        client.setPhone(temp[11]);
        client.setCountry(temp[12]);
        client.setSecurityQ(temp[13]);
        client.setSecurityA(temp[14]);
        
        /*
        System.out.println("printing Client information");
        System.out.println("FirstName"+client.getFirstName());
        System.out.println("Last Name"+client.getLastName());
        System.out.println("UserID"+client.getUserId());
        System.out.println("Password"+client.getPassword());
        */        
        HashPass.put(UserId, password);
        HashInstance.put(UserId,client);
        System.out.println("Yeah You are registered");
        out.println("Yeah You are registered");
        writeFile(UserId, password);
        
    }
    //System.out.println("Done from registration");
    
}
private String getLogInString(String UserId){
    ArrayList<String> temp = new ArrayList();
    temp=HashInstance.get(UserId).getBuddyList();
    //String [] temp1=null;
    //temp1=(String[]) temp.toArray();
    String logInString="Successfully Logged In"+",";
    for(int i=0; i<temp.size();i++){
        logInString+=temp.get(i);
        logInString+=":";
        logInString+=checkOnline(temp.get(i));
        logInString+=",";
    }
    return logInString;
    
}

public String checkOnline(String BuddyId){
    if(HashIPAddress.containsKey(BuddyId)){
        return "O";
    }
    else{
        return "I";
    }
    
}

public void getIPAddress(String s){
    String [] temp=null;
    temp= (String[]) breakString(s);
    BuddyId=temp[1];
    String IpAddress;
    IpAddress= HashIPAddress.get(BuddyId);
    out.println(IpAddress);
}
public void getPortNumber(String s){
    String [] temp=null;
    temp= (String[]) breakString(s);
    BuddyId=temp[1];
    int portNumbers;
    portNumbers= HashPortNumbers.get(BuddyId);
    out.println(portNumbers);
}

private void logIn(String logInString){
    String [] temp=null;
    temp= (String[]) breakString(logInString);   
    //System.out.println("item inside list"+temp);
    UserId=temp[1];
    password=temp[2];
    String IPAddress = null;
    IPAddress=temp[3];
    int portNumber;
    portNumber=Integer.parseInt(temp[4]);
    //System.out.println("IPAddress"+temp[3]+"<-same->"+IPAddress);
    //System.out.println(UserId);
    //System.out.println(password);
    //String serverLogInString="Successfully Logged In"+","+HashInstance.get(UserId).getBuddyList();
    
    if (HashInstance.isEmpty()){
        System.out.println("UserID is not Register: please register first");
        out.println("UserID is not Register: please register first");
    }
    else{
        if (HashInstance.containsKey(UserId)==false) {
            
            System.out.println("User doesn't exit");
            out.println("User doesn't exit");
        } 
        else {
            System.out.println("the password is:"+password.equals(HashInstance.get(UserId).getPassword()));
            if (password.equals(HashInstance.get(UserId).getPassword())){
                //System.out.println("Successfully Logged In");
                //out.println("Successfully Logged In");
                HashIPAddress.put(UserId, IPAddress);
                HashPortNumbers.put(UserId,portNumber);
                //System.out.println("IP Address of the client is "+UserId+":"+HashIPAddress.get(UserId));
                HashInstance.get(UserId).setStatus(true);
                System.out.println(this.getLogInString(UserId));
                out.println(this.getLogInString(UserId));
            }
            else{
                System.out.println("Wrong UserId or Password: Please try Again later");
                out.println("Wrong UserId or Password: Please try Again later");
            }
        }
    }  
   
    
    
}

public void sendOnlineUpdate(String BuddyId){
    ArrayList<String> temp = new ArrayList();
    temp=HashInstance.get(UserId).getBuddyList();
    String online=null;
    for(int i=0; i<temp.size();i++){
        if(checkOnline(temp.get(i)).equalsIgnoreCase("O")){
            String serverName;
            String response;
            BufferedReader in;
            PrintWriter out;
            //Socket clientSocket = null;
            try{
                Socket clientSocket = new Socket(HashIPAddress.get(temp.get(i)), HashPortNumbers.get(temp.get(i)));
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                out = new PrintWriter(clientSocket.getOutputStream(), true);
                out.println("checkOnline"+temp.get(i));
            }
            catch (IOException e){
                System.out.println("Error in communication!");
            }
            
        }
    }
}

private void logout(String logOutString){
    String [] temp=null;
    temp= (String[]) breakString(logOutString);
    UserId=temp[1];
    if (HashInstance.isEmpty()){
        System.out.println("Please Register First");
        out.println("Please Register First");
    } 
    else {
        if (HashInstance.containsKey(UserId) == false) {
            System.out.println("User doesn't exit");
            out.println("User doesn't exit");
        } 
        else if (HashInstance.get(UserId).getStatus()) {
            System.out.println(HashInstance.get(UserId).getStatus());
            HashInstance.get(UserId).setStatus(false);
            System.out.println("You are sucessfully logged off");
            out.println("You are sucessfully logged off");
            HashIPAddress.remove(UserId);
            HashPortNumbers.remove(UserId);
        } 
        else {
            System.out.println("Please LogIn First");
            out.println("Please LogIn First");
        }
    }
    
    
    
    
}
/*
private void checkStatusBuddy(String checkStatusString){
    String [] temp=null;
    temp= (String[]) breakString(checkStatusString);
    UserId=temp[1];
    BuddyId=temp[2];
    if (HashInstance.isEmpty()) {
        System.out.println("Please Register First");
        out.println("Please Register First");
    } else {
        //System.out.println("Return Type:"+""+server.HashInstance.containsKey(BuddyId));
        if (HashInstance.containsKey(UserId) == false) {
            System.out.println("User doesn't exit");
            out.println("User doesn't exit");
        } 
        else {
            if (HashInstance.containsKey(BuddyId) == false) {
                System.out.println("Buddy Id Doesn't exits, please try again later");
                out.println("Buddy Id Doesn't exits, please try again later");
            } 
            else {
                //System.out.println("Return Type:"+""+server.HashInstance.get(UserId).checkBuddy(BuddyId));
                if (HashInstance.get(UserId).checkBuddy(BuddyId) == false) {
                    System.out.println("Not your Buddy Sorry!");
                    out.println("Not your Buddy Sorry!");

                } 
                else {
                    if (HashInstance.get(BuddyId).getStatus()) {
                        System.out.println(BuddyId + "" + "is Online");
                        out.println(BuddyId + "" + "is Online");
                    } 
                    else {
                        System.out.println(BuddyId + "" + "is Offline");
                        out.println(BuddyId + "" + "is Offline");
                    }
                }
            }

        }

    }
}
 */
private void addBuddy(String addBuddyString){
    String [] temp=null;
    temp= (String[]) breakString(addBuddyString);
    UserId=temp[1];
    BuddyId=temp[2];
    if (HashInstance.isEmpty()){
        System.out.println("Please Register First");
        out.println("Please Register First");
                }
else {
        if (HashInstance.containsKey(BuddyId) == false) {
            System.out.println("Buddy doesn't exit");
            out.println("Buddy doesn't exit");
        } 
        else if (HashInstance.containsKey(BuddyId) == false) {
            System.out.println("Buddy Doesn't exit, please try again later");
            out.println("Buddy Doesn't exit, please try again later");
        } 
        else if(BuddyId.equalsIgnoreCase(UserId)){
            System.out.println("You can't add urself");
            out.println("You can't add urself");
        }
        else {
            if (HashInstance.get(UserId).checkBuddy(BuddyId)){
                System.out.println("Buddy Alrady Added");
                out.println("Buddy Alrady Added");
            }
            else{
                HashInstance.get(UserId).addBuddy(BuddyId);
                System.out.println("Buddy Added");
                //System.out.println("Buddy List is:"+HashInstance.get(UserId).getBuddyList());
                out.println("Buddy Added");
            }
            
        }
    }   
}
private void removeBuddy(String removeBuddyString){
    String [] temp=null;
    temp= (String[]) breakString(removeBuddyString);
    UserId=temp[1];
    BuddyId=temp[2];
    if (HashInstance.isEmpty()) {
        System.out.println("Please register first");
    } 
    else {
        if (HashInstance.containsKey(UserId) == false) {
            System.out.println("User doesn't exit");
            out.println("User doesn't exit");
        } 
        else if (HashInstance.containsKey(BuddyId) == false) {
            System.out.println("Buddy doesn't Exit, Please try again later");
            out.println("Buddy doesn't Exit, Please try again later");
        //BuddyId=input.nextLine();
        } 
        else {
            if (HashInstance.get(UserId).checkBuddy(BuddyId) == false) {
                System.out.println("Not your Buddy Sorry!");
                out.println("Not your Buddy Sorry!");
            } else {
                HashInstance.get(UserId).removeBuddy(BuddyId);
                System.out.println("Buddy Removed");
                out.println("Buddy Removed");
            }

        }
    }
    
    
    
    
}
}
